package com.friend.joey.applicationfriend.Fragments;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.speech.SpeechRecognizer;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.speechsynthesizer.SpeechSynthesizer;
import com.baidu.speechsynthesizer.SpeechSynthesizerListener;
import com.baidu.speechsynthesizer.publicutility.SpeechError;
import com.friend.joey.applicationfriend.Classes.Constant;
import com.friend.joey.applicationfriend.Database.MyDatabaseHelper;
import com.friend.joey.applicationfriend.Classes.JSONRequest;
import com.friend.joey.applicationfriend.MainActivity;
import com.friend.joey.applicationfriend.Adapters.MsgAdapter;
import com.friend.joey.applicationfriend.Classes.Msgtalk;
import com.friend.joey.applicationfriend.R;
import com.friend.joey.applicationfriend.Classes.TimeDeal;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static android.app.Activity.RESULT_OK;


/**
 * Created by Joey on 2017/4/20.
 */

public class FragmentTalk extends Fragment{


    private static final int REQUEST_UI = 1;
    private ArrayList<Msgtalk> msgList = new ArrayList<>();//聊天消息
    private LinearLayout fragment;
    private TextView txtLog;
    private ImageButton computer;
    private ImageButton atalk;
    private ImageButton asend;
    private EditText txtInput;
    public JSONObject baidujson;
    public JSONObject obj;
    public JSONObject result_obj;
    private MainActivity mactivity;
    private MyHandler mHandler;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;
    private DrawerLayout mDrawerLayout;
    private SpeechSynthesizer speechSynthesizer;//语音合成器
    public String sendtxt;
    public String receivetxt;

    Calendar ctime;//系统时间
    TimeDeal timedeal;
    private Toolbar toolbar;

    //Handler与聊天界面线程传数据
    private class MyHandler extends Handler{
        private WeakReference<MainActivity> mWeakReference;
        public MyHandler(MainActivity activity){
            mWeakReference=new WeakReference<MainActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity= mWeakReference.get();
            if(activity!=null){
                switch(msg.what){
                    case 1:
                        if(!"".equals(msg.obj.toString())){
                            Msgtalk rmsg = new Msgtalk(msg.obj.toString(), Msgtalk.TYPE_RECEIVED);
                            insertMsgs(rmsg);
                            mactivity.insertIntoDatabase(rmsg);
                        }
                        break;
                    case -1:
                        Toast.makeText(activity, "失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(activity, msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        break;
                    case 4:
                        Toast.makeText(activity, msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        break;
                    case -2:
                        Toast.makeText(activity, "开始合成器失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(activity, "没有信息", Toast.LENGTH_SHORT).show();
                }
            }
            else{
                Toast.makeText(getActivity(), "没有Activity", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //展示界面与变量初始化
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_talk, container, false);
        mactivity =(MainActivity)getActivity();
        fragment =(LinearLayout)view.findViewById(R.id.fragment_talk);
        mHandler = new MyHandler((MainActivity)getActivity());
        asend = (ImageButton)view.findViewById(R.id.button_asend);
        atalk = (ImageButton)view.findViewById(R.id.button_atalk);
        txtLog = (TextView)view.findViewById(R.id.text_voiceresult);
        txtInput = (EditText) view.findViewById(R.id.text_ainput);
        mDrawerLayout=(DrawerLayout)mactivity.findViewById(R.id.activity_main);
        msgRecyclerView = (RecyclerView)view.findViewById(R.id.msg_recycler_view);
        //imm = (InputMethodManager) mactivity.getSystemService(INPUT_METHOD_SERVICE);

        toolbar=(Toolbar)view.findViewById(R.id.toolbarTalk);//
        return view;
    }

    //配置及设置响应函数等
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //
        setHasOptionsMenu(true);
        if (toolbar != null) {
            toolbar.setTitle("  ");
            toolbar.setNavigationIcon(R.drawable.computer3);
        }
        mactivity.setSupportActionBar(toolbar);
        //
        //展示历史聊天信息
        initMsgs();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList,MsgAdapter.COMPUTER);
        msgRecyclerView.setAdapter(adapter);
        msgRecyclerView.scrollToPosition(msgList.size()-1);//定位到最后一行

        //语音合成设置
        speechSynthesizer = new SpeechSynthesizer(mactivity.getApplicationContext(), "holder", new MySpeechSynthesizerListener());
        speechSynthesizer.setApiKey("gxAkYuAYxKzLz8dC8vZ9RD2q", "b22e47121fe40e324d887d26bc759d49");// apiKey和secretKey
        speechSynthesizer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mactivity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setParams();

        asend.setOnClickListener(handler);
        atalk.setOnClickListener(handler);
        fragment.setOnClickListener(handler);
        txtInput.setOnClickListener(handler);
    }

    //点击Click事件绑定管理
    View.OnClickListener handler = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch(view.getId()){
                case R.id.button_asend:
                    ClickSend();
                    break;
                case R.id.button_atalk:
                    ClickTalk();
                    break;
                case R.id.fragment_talk:
                    mactivity.imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
                    break;
                case R.id.text_ainput:
                    mactivity.imm.showSoftInput(getView(),0);
                    break;
            }
        }
    };
    //点击发送按钮
    public void ClickSend(){
        mactivity.imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);//隐藏键盘；
        //获取当前时间
        timedeal = new TimeDeal(TimeDeal.INITDATE);
        String time=timedeal.GetTimeString();
        Toast.makeText(mactivity, time, Toast.LENGTH_SHORT).show();
        //线程进行json请求
        sendtxt=txtInput.getText().toString();
        //Toast.makeText(mactivity, sendtxt, Toast.LENGTH_SHORT).show();
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                Talkjson();
            }
        });

        //更新对话框显示
        if(!"".equals(sendtxt)) {
            thread.start();
            Msgtalk smsg = new Msgtalk(sendtxt, Msgtalk.TYPE_SENT);
            msgList.add(smsg);
            adapter.notifyItemChanged(msgList.size()-1);//有新消息时刷新显示
            msgRecyclerView.scrollToPosition(msgList.size()-1);//定位到最后一行
            txtInput.setText("");//清空输入框的内容
            //添加进数据库
            mactivity.insertIntoDatabase(smsg);
        }
        else{
            Toast.makeText(mactivity, "空信息无法发送", Toast.LENGTH_SHORT).show();
        }
    }
    //封装聊天回复请求json
    private void Talkjson(){
        Message message = mHandler.obtainMessage();
        message.what = 0;
        obj=new JSONObject();
        try {
            //obj.put("text",txtInput.getText().toString());
            obj.put("text",sendtxt);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String url= "http://10.242.90.85:8000/jsontest" ;
        //String url= "http://172.20.10.5:8000/jsontest";
        //String url = "http://oldassistant.applinzi.com/jsontest";
        JSONRequest test1=new JSONRequest(obj,url);
        result_obj = test1.jsonRequest();
        try {
            message.obj = result_obj.getString("result");
            message.what=1;
            int k=speakBD(result_obj.getString("result"));
            if(k<0) {
                message.what=-2;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message.what=-1;
        }

        mHandler.sendMessage(message);
    }
    //点击说话按钮
    private void ClickTalk(){
        mactivity.imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
        start();
    }

    //菜单项管理
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                //Toast.makeText(mactivity,"侧边栏",Toast.LENGTH_SHORT).show();
                mactivity.showDrawer();
                break;
        }
        return true;
    }

    // 初始化语音合成客户端并启动
    private void setParams() {
        speechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        speechSynthesizer.setParam(SpeechSynthesizer.PARAM_VOLUME, "5");
        speechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEED, "5");
        speechSynthesizer.setParam(SpeechSynthesizer.PARAM_PITCH, "5");
        speechSynthesizer.setParam(SpeechSynthesizer.PARAM_AUDIO_ENCODE, SpeechSynthesizer.AUDIO_ENCODE_AMR);
        speechSynthesizer.setParam(SpeechSynthesizer.PARAM_AUDIO_RATE, SpeechSynthesizer.AUDIO_BITRATE_AMR_15K85);
    }
    public int speakBD(String content){
        //初始化语音合成客户端并启动
        int ret = speechSynthesizer.speak(content);
        if (ret != 0) {
            //Toast.makeText(mactivity, "开始合成器失败", Toast.LENGTH_SHORT).show();
            return -1;
        }else{
            //Toast.makeText(mactivity, "开始合成器成功", Toast.LENGTH_SHORT).show();
            return 0;
        }
    }
    public class MySpeechSynthesizerListener implements SpeechSynthesizerListener{

        @Override
        public void onStartWorking(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onSpeechStart(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onNewDataArrive(SpeechSynthesizer speechSynthesizer, byte[] bytes, boolean b) {

        }

        @Override
        public void onBufferProgressChanged(SpeechSynthesizer speechSynthesizer, int i) {

        }

        @Override
        public void onSpeechProgressChanged(SpeechSynthesizer speechSynthesizer, int i) {

        }

        @Override
        public void onSpeechPause(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onSpeechResume(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onCancel(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onSynthesizeFinish(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onSpeechFinish(SpeechSynthesizer speechSynthesizer) {

        }

        @Override
        public void onError(SpeechSynthesizer speechSynthesizer, SpeechError speechError) {

        }
    }


    //启动百度语音识别对话框
    private void start() {
        Intent recognizerIntent = new Intent();
        recognizerIntent.setAction("com.baidu.action.RECOGNIZE_SPEECH");
        bindParams(recognizerIntent); //TODO 为recognizerIntent设置参数，支持的参数见本文档的“识别参数”一节
        // 为了支持离线识别能力，请参考“离线语音识别参数设置”一节
        try{
            //Toast.makeText(mactivity, "之前", Toast.LENGTH_SHORT).show();
            startActivityForResult(recognizerIntent, REQUEST_UI);
            //Toast.makeText(mactivity, "之后", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e){
            e.printStackTrace();
            //txtLog.setText(e.toString());
            Toast.makeText(mactivity, "异常", Toast.LENGTH_SHORT).show();
        }
    }
    void bindParams(Intent intent) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mactivity);
        if (sp.getBoolean("tips_sound", true)) {
            intent.putExtra(Constant.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start);
            intent.putExtra(Constant.EXTRA_SOUND_END, R.raw.bdspeech_speech_end);
            intent.putExtra(Constant.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
            intent.putExtra(Constant.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error);
            intent.putExtra(Constant.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);
            intent.putExtra("nlu","enable");
            intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard1/afriend/s_1.txt");
            //intent.putExtra(Constant.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1");
        }
    }
    //百度语音对话框回调函数
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            ArrayList<String> results = data.getStringArrayListExtra(SpeechRecognizer.RESULTS_RECOGNITION);
            String result=results.toString();
            result=result.substring(1,result.length()-1);
            //txtInput.setText(result);
            setInputText(result);
            String json_res = data.getStringExtra("origin_result");
            try {
                baidujson= new JSONObject(json_res);
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(mactivity, "json异常", Toast.LENGTH_SHORT).show();
            }
            //显示json格式结果，但是会造成界面乱码，调试用
            try {
                txtLog.setText(new JSONObject(json_res).toString(4));
            } catch (JSONException e) {
                e.printStackTrace();
                txtLog.setText("origin_result=[warning: bad json]\n" + json_res);
            }
            // data.get... TODO 识别结果包含的信息见本文档的“结果解析”一节
        }
    }

    public void setInputText(String text){
        txtInput.setText(text);
    }

    //初始化聊天列表
    private void initMsgs(){
        Msgtalk msg0;
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(mactivity,"TestTalk.db",null,2);//数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("talk",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            while(cursor.moveToNext())
            {
                String datatext= cursor.getString(cursor.getColumnIndex("txt"));
                int dataType=cursor.getInt(cursor.getColumnIndex("side"));
                msg0=new Msgtalk(datatext,dataType);
                msgList.add(msg0);
            }
           //txtInput.setText(datatext);
        }
        else{
            Msgtalk msg1= new Msgtalk("大笨蛋你好",Msgtalk.TYPE_RECEIVED);
            msgList.add(msg1);
            Msgtalk msg2= new Msgtalk("大傻瓜你好",Msgtalk.TYPE_SENT);
            msgList.add(msg2);
            Msgtalk msg3= new Msgtalk("两个月你好",Msgtalk.TYPE_RECEIVED);
            msgList.add(msg3);
            Toast.makeText(mactivity, "数据库未获取到信息", Toast.LENGTH_SHORT).show();
        }
    }
    //插入一条信息
    public void insertMsgs(Msgtalk msg){
        msgList.add(msg);
        adapter.notifyItemChanged(msgList.size()-1);//有新消息时刷新显示
        msgRecyclerView.scrollToPosition(msgList.size()-1);//定位到最后一行
    }
    //延时滚动屏幕未完成
    private void scrollforInput(){
        /*new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);//休眠3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Toast.makeText(mactivity, "滑动", Toast.LENGTH_SHORT).show();
                try {
                    Thread.sleep(1000 );//休眠3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //msgRecyclerView.scrollToPosition(msgList.size()-1);
                Toast.makeText(mactivity, "滑动成功", Toast.LENGTH_SHORT).show();
            }
        }.start();*/
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
    //加载fragment类
    public static FragmentTalk newInstance(String arg){
        FragmentTalk FragmentTalk = new FragmentTalk();
        Bundle args = new Bundle();
        args.putString("fTalk", arg);
        FragmentTalk.setArguments(args);
        return FragmentTalk;
    }

}
